angular.module('baisonDb', [])
        //打开数据库 ===========================================================
        .factory('dbOpen', ['$q', function ($q) {
                var deferred = $q.defer();
                var promise = deferred.promise;
                var openDatabase = function (name, path) {
                    baison_app.db.openDatabase({name: name, path: path}, function (ret, err) {
                        if (!ret.status) {
                            openDatabase(name, path);
                        } else {
                            deferred.resolve('success');
                        }
                    });
                    return promise;
                };
                return {
                    openDatabase: openDatabase
                };

            }
        ])

         //数据库初始化 =========================================================
        .factory('dbInit', ['$q', '$http', function ($q, $http) {
                var installSql;
                var deferredInstall = {};
                var promiseInstall = {};
                var executeSql = function (promiseInstall,deferredInstall,installSql,name,index,sqls_arr) {
                    var o = sqls_arr[index];
                    
                    if(!o){
                        deferredInstall[o].resolve('false');
                        return;
                    }
                    var sql = installSql.sqls[o];
                    baison_app.db.executeSql({'name': name, 'sql': sql}, function (ret, err) {
                        if (!ret.status) {
                            executeSql(promiseInstall,deferredInstall,installSql,name,index,sqls_arr);
                        } else {
                            deferredInstall[o].resolve(o + '执行成功!');
                            index++;
                            executeSql(promiseInstall,deferredInstall,installSql,name,index,sqls_arr);
                        }
                    });
                };
                return function (name) {
                    //载入安装sql
                    return $http.get('./install/YsPos.json').then(function (response) {
                        installSql = response.data;
                        var sqls_arr = Object.keys(installSql.sqls);
                        if(sqls_arr.length <= 0){
                            var deferred = $q.defer();
                            var promise = deferred.promise;
                            deferred.resolve('success');
                            return promise;
                        }
                        for(var i = 0; i <= sqls_arr.length ; i++){
                            var o = sqls_arr[i];
                            deferredInstall[o] = $q.defer();
                            promiseInstall[o] = deferredInstall[o].promise;
                        }
                        var index = 0;
                        //执行安装sql脚本
                        executeSql(promiseInstall,deferredInstall,installSql,name,index,sqls_arr);
                        return $q.all(promiseInstall);
                    });
                };
            }])
        //数据库版本处理
        .factory('dbVesionInit', ['$q', '$http', function ($q, $http) {
                var installSql;
                var deferredInstall = {};
                var promiseInstall = {};
                var executeSql = function (promiseInstall,deferredInstall,installSql,name,index,sqls_arr) {
                    var o = sqls_arr[index];
                    if(!o){
                        deferredInstall[o].resolve("false");
                        return;
                    }
                    
                    var sql = installSql[o];
                    baison_app.db.executeSql({'name': name, 'sql': sql}, function (ret, err) {
                        if (!ret.status) {
                            executeSql(promiseInstall,deferredInstall,installSql,name,index,sqls_arr);
                        } else {
                            deferredInstall[o].resolve(o + '执行成功!');
                            index++;
                            executeSql(promiseInstall,deferredInstall,installSql,name,index,sqls_arr);
                            
                        }
                    });
                };
                return function (name,version) {
                    //载入安装sql
                    return $http.get('./install/YsPos.json').then(function (response) {
                        installSql = response.data;
                        //执行安装sql脚本
                        var sqls_arr = Object.keys(installSql[version]);
                        if(sqls_arr.length <= 0){
                            var deferred = $q.defer();
                            var promise = deferred.promise;
                            deferred.resolve('success');
                            return promise;
                        }
                        for(var i = 0; i <= sqls_arr.length ; i++){
                            var o = sqls_arr[i];
                            deferredInstall[o] = $q.defer();
                            promiseInstall[o] = deferredInstall[o].promise;
                        }
                        var index = 0;
                        executeSql(promiseInstall,deferredInstall,installSql[version],name,index,sqls_arr);
                        
                        return $q.all(promiseInstall);
                    });
                };
            }])
        //额外数据初始化 =======================================================
        .factory('appInit', ['$q', '$http', function ($q, $http) {
                var firstLaunch = $api.getStorage('firstLaunch');
                var _configData = $api.getStorage('configData');
                return function () {
                    //console.log(_configData);
                };
            }])
        //数据库增删改 =========================================================
        .factory('dbExec', ['$q', function ($q) {
            return function (db, sql) {
                var deferred = $q.defer();
                var promise = deferred.promise;

                baison_app.db.executeSql({name: db, sql: sql}, function (ret, err) {
                    if (!ret.status) {
                        deferred.reject(err.msg);
                    } else {
                        deferred.resolve('success');
                    }
                });
                return promise;
            };
        }])
        .factory('dbReplaceInto',['$q','$rootScope',function($q,$rootScope){
			//一次插入数据表的行数
			var insert_record_num = 500;
			//拼接values值 
			var get_values_str = function(values){
				var values_str = '';
				$.each(values, function (i, n) {
					values_str += "'"+n +"'" + ',';
				});
				
				return values_str;
			};
			//拼接fields值
			var get_fields_str = function(fields){
				var fields_str = '';
				$.each(fields, function (i, n) {
					fields_str += n + ',';
				});
				
				return fields_str;
			};
            var executeSql_deal = function(deferred,index,fornum,sqlnum,tb, data,field){

                if(index >= fornum){
					return;
				}
                //拼接 字段
				var sqlfields = get_fields_str(field); 
				sqlfields = sqlfields.substr(0,sqlfields.length-1);
				var sql_string = "REPLACE INTO "+ tb +"("+sqlfields+") VALUES";
				var sql_init = index*sqlnum;
				var count_num = (index +1)*sqlnum;
				count_num = count_num > data.length ?data.length:count_num;
                for(var j = sql_init;j<count_num;j++){
                    //拼接values值
                    var values = '';
                    values += get_values_str(data[j]);
                    values = values.substr(0,values.length -1);
                    sql_string += "("+values+"),";
                }
                sql_string = sql_string.substr(0,sql_string.length-1);
                baison_app.db.executeSql({name:'YsPos',sql:sql_string},function(ret,err){
                    if(!ret.status){
                        deferred[index].resolve('success');
                        console.log(err);
                    }else{
                        deferred[index].resolve('success');
                    }
                    index++;
                    executeSql_deal(deferred,index,fornum,sqlnum,tb,data,field);
                });
                
            };
			return function(tb, data,field){
				if(data.length <= 0){
					var deferred = $q.defer();
					var promise = deferred.promise;
                    deferred.resolve('false');
					return promise;
				}
				var deferred = {};
				var promise = {};
				//插入数据总行数 
				var data_len = data.length;
				var insert_record_num = 500; //暂时这么写
				//循环插入次数
				var fornum = data_len <= insert_record_num ? 1:Math.ceil(data_len/insert_record_num);
				//拼接sql语句次数
				var sqlnum = data_len <= insert_record_num ? data_len : insert_record_num;
				//console.log(fornum);
				//console.log(sqlnum);
				var index = 0;
				for(var i = 0; i < fornum ;i++){
					deferred[i] = $q.defer();
					promise[i] = deferred[i].promise;
				}
				executeSql_deal(deferred,index,fornum,sqlnum,tb, data,field);
				return $q.all(promise);
			}
        }])
        //数据库批量替换 =========================================================
        .factory('dbReplace', ['$q', function ($q) {

                /**
                 * 替换插入
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-10-23
                 * @param {string} tb 表名
                 * @param {array} data 插入的数据
                 * @param {array} key 唯一索引，为数组，可以and联合判断唯一性冲突
                 * @param {array} field 覆盖字段，如果冲突需要update的字段
                 * @example dbReplace('PosCheck',[{CheckCode:'001',CheckName:'现金'},{CheckCode:'002',CheckName:'银行卡'},{CheckCode:'003',CheckName:'微信'}],[CheckCode],[CheckCode,CheckName]);
                 */
                return function (tb, data, key, field) {
                    var deferred = {};
                    var promise = {};

                    var sql_select;
                    var sql_where;
                    $.each(data, function (i, n) {
                        deferred[i] = $q.defer();
                        promise[i] = deferred[i].promise;

                        sql_where = sql_select = '';

                        for (var i2 = 0; i2 < key.length; i2++) {
                            var k = key[i2];
                            sql_where = sql_where + ' and ' + k + '="' + n[k] + '" ';
                        }

                        sql_select = 'select * from ' + tb + ' where 1=1 ' + sql_where;

                        baison_app.db.selectSql({name: 'YsPos', sql: sql_select}, function (ret, err) {
                            var sql_insert, sql_update;
                            var sql_update_where, sql_update_value, sql_insert_field, sql_insert_value;
                            sql_update_where = sql_update_value = sql_insert_field = sql_insert_value = '';

                            for (var i0 = 0; i0 < key.length; i0++) {
                                var k = key[i0];
                                sql_update_where = sql_update_where + ' and ' + k + '="' + n[k] + '" ';
                            }

                            for (var i3 = 0; i3 < field.length; i3++) {
                                var f = field[i3];
                                sql_update_value = sql_update_value + f + '="' + n[f] + '",';
                            }

                            for (var u in n) {
                                sql_insert_field = sql_insert_field + u + ',';
                                sql_insert_value = sql_insert_value + '"' + n[u] + '",';
                            }

                            //去掉末位逗号
                            sql_update_value = sql_update_value.substring(0, sql_update_value.length - 1);
                            sql_insert_field = sql_insert_field.substring(0, sql_insert_field.length - 1);
                            sql_insert_value = sql_insert_value.substring(0, sql_insert_value.length - 1);

                            sql_insert = 'insert into ' + tb + ' (' + sql_insert_field + ') values (' + sql_insert_value + ')';
                            sql_update = 'update ' + tb + ' set ' + sql_update_value + ' where 1=1 ' + sql_update_where;
                            if (ret.status) {
                                if (ret.data.length > 0) {
                                    //存在冲突则更新
                                    baison_app.db.executeSql({name: 'YsPos', sql: sql_update}, function (ret, err) {
                                        if (!ret.status) {
                                            deferred[i].reject(err.msg);
                                        } else {
                                            deferred[i].resolve('success');
                                        }
                                    });
                                } else {
                                    //不存在冲突则插入
                                    baison_app.db.executeSql({name: 'YsPos', sql: sql_insert}, function (ret, err) {
                                        if (!ret.status) {
                                            deferred[i].reject(err.msg);
                                        } else {
                                            deferred[i].resolve('success');
                                        }
                                    });
                                }
                            } else {
                                deferred[i].reject(err.msg);
                            }
                        });
                    });
                    return $q.all(promise);
                };
            }])
        //数据库增查询 =========================================================
        .factory('dbSelect', ['$q', function ($q) {
                return function (db, sql) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.selectSql({name: db, sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
                };
            }])
			//数据库增查询 =========================================================
        .factory('dbSelect_rewirte', ['$q', function ($q) {
                
				var cx_select = function(db, sql){
					var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.selectSql({name: db, sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
					
				}
				return {
					cx_select:cx_select,
				};
            }])

        //根据条件进行更新 =====================================================
        .factory('dbUpdate', ['$q', function ($q) {
                /**
                 * 编辑保存
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-06-13
                 * @param {string} tb 表名
                 * @param {object} data 更新的数据
                 * @param {object} where 更新条件，可以and联合判断
                 **/
                return function (tb, data, where) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;

                    var sql_update_value, sql_update_where;
                    sql_update_value = sql_update_where = '';

                    for (var u in data) {
                        sql_update_value = sql_update_value + u + '="' + data[u] + '",';
                    }

                    for (var w in where) {
                        sql_update_where = ' and ' + w + '="' + where[w] + '" ';
                    }

                    sql_update_value = sql_update_value.substring(0, sql_update_value.length - 1);
                    var sql = 'update ' + tb + ' set ' + sql_update_value + ' where 1=1 ' + sql_update_where;
                    baison_app.db.executeSql({name: 'YsPos', sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            //出错处理
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
                };
            }])
        //更新字段值，是在字段本身上增加数值
        .factory('dbUpdateAdd', ['$q', function ($q) {
                /**
                 * 编辑保存
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-06-13
                 * @param {string} tb 表名
                 * @param {object} data 更新的数据
                 * @param {object} where 更新条件，可以and联合判断
                 **/
                return function (tb, data, where) {

                    var deferred = $q.defer();
                    var promise = deferred.promise;

                    var sql_update_value, sql_update_where;
                    sql_update_value = sql_update_where = '';
                    for (var u in data) {
                        if (data[u].add) {
                            sql_update_value = sql_update_value + data[u].field + '=' + data[u].field + '+"' + data[u].value + '",';
                        } else {
                            sql_update_value = sql_update_value + data[u].field + '="' + data[u].value + '",';
                        }

                    }

                    for (var w in where) {

                        sql_update_where += ' and ' + w + '="' + where[w] + '" ';
                    }

                    sql_update_value = sql_update_value.substring(0, sql_update_value.length - 1);
                    var sql = 'update ' + tb + ' set ' + sql_update_value + ' where 1=1 ' + sql_update_where;
                    //baison_app.api.alert({msg:sql,title:'updateadd'});
                    baison_app.db.executeSql({name: 'YsPos', sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            //出错处理

                            deferred.reject(err.msg);
                        } else {

                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
                };
            }])
        //删除操作=============================================================
        .factory('dbDelete', ['$q', function ($q) {
                /**
                 * 删除
                 * @author hunter
                 * @param {string} tb 表名
                 * @param {object} where 条件{'x':1,'y':2}
                 */
                return function (tb, where) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var sql_where = '';
                    for (var w in where) {
                        sql_where = ' and ' + w + '="' + where[w] + '" ';
                    }
                    var sql = 'delete from ' + tb + ' where 1=1 ' + sql_where;
                    
                    baison_app.db.executeSql({name: 'YsPos', sql: sql}, function (ret, err) {
                        
                        if (!ret.status) {
                            //出错处理
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
                };
            }])
            .factory('dbDelete_sql', ['$q', function ($q) {
                return function (tb, sql_where) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var sql = 'delete from ' + tb +  sql_where;
                    
                    baison_app.db.executeSql({name: 'YsPos', sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            //出错处理
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve(ret.data);
                        }
                    });
                    return promise;
                };
            }])
        //直接新增 ============================================================
        .factory('dbInsert', ['$q', function ($q) {
                /**
                 * 直接新增
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-06-13
                 * @param {string} tb 表名
                 * @param {object} data 单条插入的数据
                 */
                return function (tb, data) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;

                    var sql_insert_value, sql_insert_field;
                    sql_insert_value = sql_insert_field = '';

                    for (var u in data) {
                        sql_insert_field = sql_insert_field + u + ',';
                        sql_insert_value = sql_insert_value + '"' + data[u] + '",';
                    }
                    sql_insert_field = sql_insert_field.substring(0, sql_insert_field.length - 1);
                    sql_insert_value = sql_insert_value.substring(0, sql_insert_value.length - 1);
                    var sql_insert = 'insert into ' + tb + ' (' + sql_insert_field + ') values (' + sql_insert_value + ')';
                    baison_app.db.executeSql({name: 'YsPos', sql: sql_insert}, function (ret, err) {
                        if (!ret.status) {
                            //出错处理
                            deferred.reject(err.msg);
                        } else {
                            deferred.resolve('');
                        }
                    });
                    return promise;
                };
            }])

        //批量新增 不判重，盘重请用replace =======================================
        .factory('dbInsertMulti', ['$q', 'dbInsert', function ($q, dbInsert) {
                /**
                 * 直接新增
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-11-09
                 * @param {string} tb 表名
                 * @param {array} data 批量插入数据的数组
                 */
                return function (tb, data) {
                    var promise = [];
                    data.forEach(function (e, index) {
                        var p = dbInsert(tb, e);
                        promise.push(p);
                    });
                    return $q.all(promise);
                };
            }])

        //获取单条 ============================================================
        .factory('dbGetOne', ['$q', function ($q) {
                /**
                 * 获取单条数据
                 * @param {string} sql
                 * @returns {object} Promise
                 */
                return function (sql) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.selectSql({name: 'YsPos', sql: sql}, function (ret, err) {
                        if (!ret.status) {
                            //出错处理
                            deferred.reject(err.msg);
                        } else {
                            if (ret.data.length > 0) {
                                deferred.resolve(ret['data'][0]);
                            } else {
                                deferred.resolve(0);
                            }
                        }
                    });
                    return promise;
                };
            }])


        //added by lqx maowei on 20170116 获取单条同步 ============================================================
        .factory('dbGetOneSync', ['$q', function ($q) {
                /**
                 * 获取单条数据
                 * @param {string} sql
                 * @returns {object} Promise
                 */
                return function (sql) {
                    var ret = baison_app.db.selectSqlSync({
                        name: 'YsPos',
                        sql: sql
                    });
                    return ret.data[0];
                };
            }])

        //事务操作 ============================================================
        .factory('dbTrans', ['$q', function ($q) {
                var begin = function () {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.transaction({
                        'name': 'YsPos',
                        'operation': 'begin'
                    }, function (ret, err) {
                        if (ret.status) {
                            deferred.resolve('事务操作成功');
                        } else {
                            deferred.reject(err.msg);
                        }
                    });
                    return promise;
                };

                var commit = function () {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.transaction({
                        'name': 'YsPos',
                        'operation': 'commit'
                    }, function (ret, err) {
                        if (ret.status) {
                            deferred.resolve('事务提交成功');
                        } else {
                            deferred.reject(err.msg);
                        }
                    });
                    return promise;
                };

                var rollback = function () {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    baison_app.db.transaction({
                        'name': 'YsPos',
                        'operation': 'rollback'
                    }, function (ret, err) {
                        if (ret.status) {
                            deferred.resolve('事务回滚成功');
                        } else {
                            deferred.reject(err.msg);
                        }
                    });
                    return promise;
                };

                return {
                    'begin': begin,
                    'commit': commit,
                    'rollback': rollback
                };
            }])
        ;